package com.hannesdorfmann.mosby3.mvi.integrationtest.backstack;

import com.hannesdorfmann.mosby3.mvi.integrationtest.ResourceTable;
import com.hannesdorfmann.mosby3.mvi.integrationtest.backstack.first.FirstMviFraction;
import com.hannesdorfmann.mosby3.mvi.integrationtest.backstack.first.FirstPresenter;
import com.hannesdorfmann.mosby3.mvi.integrationtest.backstack.second.SecondMviFraction;
import com.hannesdorfmann.mosby3.mvi.integrationtest.backstack.second.SecondPresenter;
import com.hannesdorfmann.mosby3.mvi.integrationtest.slice.BackstackAbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.bundle.AbilityInfo;

import java.util.concurrent.atomic.AtomicInteger;

public class BackstackAbility extends FractionAbility {

    public final static FirstPresenter firstPresenter = new FirstPresenter();
    public final static SecondPresenter secondPresenter = new SecondPresenter();
    public final static AtomicInteger createFirstPresenterCalls = new AtomicInteger(0);
    public final static AtomicInteger createSecondPresenterCalls = new AtomicInteger(0);

    private static volatile BackstackAbility currentInstance;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_backstack);

        currentInstance = getInstance();

        getFractionManager()
                .startFractionScheduler()
                .replace(ResourceTable.Id_stackContainer, new FirstMviFraction())
                .submit();

    }

    public static BackstackAbility getInstance(){
        if(BackstackAbility.currentInstance == null){
            BackstackAbility.currentInstance = new BackstackAbility();
        }
        return  BackstackAbility.currentInstance;
    }

    public static void navigateToSecondFragment() {
        currentInstance.getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override public void run() {

                currentInstance.getFractionManager()
                        .startFractionScheduler()
                        .replace(ResourceTable.Id_stackContainer, new SecondMviFraction())
                        .pushIntoStack(null)
                        .submit();
            }
        });

    }

    public static void rotateToLandscape() {
        currentInstance.setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);
    }

    public static void rotateToPortrait() {
        currentInstance.setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
    }

    public static void pressBackButton() {
        currentInstance.getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override public void run() {
                currentInstance.onBackPressed();
            }
        });
    }
}
